package com.mn.ble.s

import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.bluetooth.le.AdvertiseCallback
import android.bluetooth.le.AdvertiseData
import android.bluetooth.le.AdvertiseSettings
import android.bluetooth.le.BluetoothLeAdvertiser
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.ParcelUuid
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.util.*


class MainActivity : AppCompatActivity() {


    private val isAdvertising: Boolean = false
    private var mBluetoothAdapter: BluetoothAdapter? = null

    companion object {
        fun jump(c: Context) {
            c.startActivity(Intent(c, MainActivity::class.java))
        }
    }


    var mButton: Button? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mButton = findViewById(R.id.board)
        mButton?.setOnClickListener {
            startBleBroadcast()
        }
        check()
    }


    private val advertiseCallback = object : AdvertiseCallback() {
        override fun onStartSuccess(settingsInEffect: AdvertiseSettings?) {
            super.onStartSuccess(settingsInEffect)
            runOnUiThread {
                mButton?.setText("onStartSuccess")
            }
        }

        override fun onStartFailure(errorCode: Int) {
            super.onStartFailure(errorCode)
            runOnUiThread {
                mButton?.setText("onStartFailure:" + errorCode)
            }
        }
    }

    private val uniqueIdentifier = "ABC" // 您的唯一标识


    @SuppressLint("MissingPermission")
    private fun startBleBroadcast() {

        if (mBluetoothAdapter == null) {
            return
        }
        if (!mBluetoothAdapter!!.isMultipleAdvertisementSupported) {
            Toast.makeText(this, "不支持", Toast.LENGTH_SHORT).show()
            return
        }

        val advertiseSetting = AdvertiseSettings.Builder()
            // 广播模式，控制广播功率和延迟
            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY)
            // 广播发射功率级别
            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH)
            // 广播超时时间，最大值为 3*60*1000 毫秒，为 0 时禁用超时，默认无限广播
            .setTimeout(0) // 广播连接类型
            .setConnectable(true)
            .build()


        //UUID不能乱写，比如这个0000ffff-0000-1000-2000-300000000000就没用，会开启失败
        //详情见  蓝牙开发常用UUID表 https://blog.csdn.net/qq_30596077/article/details/88641583
//        val switcherUuid = UUID.fromString("0000ffff-0000-1000-2000-300000000000")
        val switcherUuid = UUID.fromString("0000180D-0000-1000-8000-00805F9B34FB")

        val advertiseData = AdvertiseData.Builder()
            // 广播是否包含设备名称
            .setIncludeDeviceName(true)
            // 广播是否包含发射功率
            .setIncludeTxPowerLevel(true)
            // 添加服务uuid
            .addServiceUuid(ParcelUuid(switcherUuid))
            //TODO 这里设置广播 !!!!!
            .addManufacturerData(0x0001,uniqueIdentifier.toByteArray())
//            .addServiceData(ParcelUuid(switcherUuid), byteArrayOf(1, 2, 3, 4))
            .build()

        //扫描响应数据，当客户端扫描是才响应（可选参数）
        val advertiseResData = AdvertiseData.Builder()
            // 添加自定义服务数据
            .addServiceData(ParcelUuid(UUID.randomUUID()), byteArrayOf(1, 2, 3, 4))
            // 添加自定义厂商数据
            .addManufacturerData(0x06, byteArrayOf(5, 6, 7, 8)).build()


        if (mBluetoothAdapter!!.isEnabled) {
            // 设置广播设备的名称，方便搜索
            mBluetoothAdapter!!.name = "JYF--001"
            // 获取广播类
            val bluetoothLeAdvertiser: BluetoothLeAdvertiser =
                mBluetoothAdapter!!.bluetoothLeAdvertiser
            if (!isAdvertising) {
                // 开始广播
//                bluetoothLeAdvertiser.startAdvertising(
//                    advertiseSetting, advertiseData, advertiseCallback
//                )
                bluetoothLeAdvertiser.startAdvertising(
                    advertiseSetting, advertiseData, advertiseResData, advertiseCallback
                )
            }
        }
    }

    @SuppressLint("MissingPermission")
    private fun check() {
        // 判断支持蓝牙功能
        if (packageManager.hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            // 获取蓝牙管理服务
            val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
            // 获取蓝牙适配器
            mBluetoothAdapter = bluetoothManager.adapter
            if (mBluetoothAdapter != null) {
                if (!mBluetoothAdapter!!.isEnabled) {
                    mBluetoothAdapter!!.enable()
                }
            }
        }

    }


}